import jQuery from 'jquery';
import {ScriptRender} from "../../utils/ScriptRender";
import {stringUtils} from "../../utils/stringUtils";
import {MidwayConfig} from "../midway";

const moduleDOMTemplate = "<div class='module_${module}' id='${id}'></div>";
const cssReg = /url\s*\(\s*(['"]?)(resources[\\/].*?)\1\s*\)/ig;
const cssUrlTemplate = 'url("${base}/${code}/${name}")';

export const ModuleRender = {
    render: (key, code, style, view, container, attrs) => {
        //渲染Module的样式部分
        if (style) {
            const exists = ScriptRender.checkStyle(item => {
                if(item.attributes['moduleCode']) {
                    return item.attributes['moduleCode'].value === code;
                }
                return false;

            });
            //如果不存在样式,则添加进去
            if (!exists) {
                let styleStr = style.toString();
                let css = styleStr.replace(cssReg, function ($0, $1, $2) {
                    return stringUtils.applyTemplate(cssUrlTemplate, {base: MidwayConfig.BundlePath, code, name: $2})
                });
                ScriptRender.addEmbedStyle(css, {moduleCode: code});
            }
        }
        if(view) {
            //渲染Module的Template
            const element = jQuery.parseHTML(stringUtils.applyTemplate(moduleDOMTemplate, {
                "module": code,
                "id": key
            }))[0];
            if(attrs) {
                for(let key in attrs) {
                    if(key === 'style') {
                        for(let styleKey in attrs[key]) {
                            element.style[styleKey] = attrs[key][styleKey];
                        }
                    } else {
                        element.setAttribute(key, attrs[key]);
                    }
                }
            }
            element.appendChild(view);
            container.appendChild(element);
        }
    }
};